package com.ray.aopdemo.aop;

import com.ray.aopdemo.annotation.LogAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * User: Ray.Shaw <p />
 * Time: 2019/11/1 15:48  <p />
 * Version: V1.0  <p />
 * Description: service日志 <p />
 */
@Component
@Aspect
@Slf4j
public class ServiceLogAspect {

    @Pointcut("@annotation(com.ray.aopdemo.annotation.LogAnnotation)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public void around(ProceedingJoinPoint point) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MethodSignature signature  = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        // 记录下请求内容
        log.info("=============我来源与Before========================");
        log.info("logAnnotation:[module:{}, operation{}]", logAnnotation.module(), logAnnotation.operation());
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(point.getArgs()));
    }
}
